from django.utils import simplejson as json
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.db import Key
from models import Event, User, EventAttendee, DEFAULT_DATETIME_FORMAT
from json import encode
import time, datetime

class JsonHandler(webapp.RequestHandler):
    def get_params(self):
        return json.loads(self.request.body)
    
    def write(self, result):
        self.response.headers['Content-Type'] = 'application/json'
        self.response.out.write(encode(result))

class EventHandler(JsonHandler):
    def post(self, event_id):
        params = self.get_params()
        event = Event(description = params['description'], times = [datetime.datetime.fromtimestamp(time.mktime(time.strptime(t, DEFAULT_DATETIME_FORMAT))) for t in params['times']], host = User.all().filter('name = ', params['host']).get())
        event.put()
        for name in params['attendees']:
            EventAttendee(event = event, user = User.all().filter('name = ', name).get()).put()
        self.write({'id': event.key().id()})
        
    def get(self, event_id):
        event = Event.get(Key.from_path('Event', int(event_id)))
        if event:
            event.update_counts()
            self.write(event.as_map())
        else:
            self.response.set_status(404)
        
    def delete(self, event_id):
        event = Event.get(Key.from_path('Event', int(event_id)))
        event.delete() if event else self.response.set_status(404)
        
class EventAttendeeHandler(JsonHandler):
    def get(self, event_id):
        self.write(Event.get(Key.from_path('Event', int(event_id))).as_map()['attendees'])
        
    def put(self, event_id):
        params = self.get_params()
        event = Event.get(Key.from_path('Event', int(event_id)))
        available = []
        for a in params['available']:
            t = datetime.datetime.fromtimestamp(time.mktime(time.strptime(a, DEFAULT_DATETIME_FORMAT)))
            if t not in event.times:
                self.response.set_status(500)
                self.write({'message': 'Available time is not in the time range of event.'})
                return
            available.append(t)
        attendee = EventAttendee.gql('WHERE event = :1 AND user = :2', event, User.all().filter('name = ', params["user"]).get()).get()
        attendee.available = available
        attendee.updated = datetime.datetime.now() 
        attendee.put()
        event.update_counts()
        self.write(attendee)
        
    def delete(self, event_id, username):
        EventAttendee.all().filter('event = ', Event.get(Key.from_path('Event', int(event_id)))).filter('user = ', User.all.filter('name = ', username).get()).get().delete()
        

class EventListHandler(JsonHandler):
    def get(self, tense):
        #result = Event.all().filter('host = ', params['hosts'])
        events = Event.all()
        now = datetime.datetime.now()
        result = []
        if tense == 'past':
            events = events.filter('times < ', now)
        elif tense == 'future':
            events = events.filter('times > ', now)
        for event in events:
            event.update_counts()
            result.append(event.as_map())
        self.write(result)

class FriendListHandler(JsonHandler):
    def get(self):
        self.write(User.all().fetch(1000))

app = webapp.WSGIApplication([
                              (r'/api/event/?([0-9]+)?', EventHandler),
                              (r'/api/events/?(past|future)?', EventListHandler),
                              (r'/api/event/([0-9]+)/attendees?', EventAttendeeHandler),
                              (r'/api/event/([0-9]+)/attendee/(.*)', EventAttendeeHandler),
                              ('/api/friends', FriendListHandler),
                            ], debug=True)

def main():
    run_wsgi_app(app)

if __name__ == '__main__':
    main()